<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, getUserProfile, updateUserProfile } from '../services/auth'

const router = useRouter()
const userData = ref(null)
const isLoading = ref(true)
const error = ref('')

// 会员等级定义
const membershipLevels = [
  {
    id: 'basic',
    name: '普通会员',
    price: 0,
    period: '永久',
    features: [
      '基础视频观看功能',
      '每日5次视频下载',
      '标准画质',
      '基础评论功能'
    ],
    highlight: false
  },
  {
    id: 'premium',
    name: '高级会员',
    price: 19,
    period: '月',
    features: [
      '所有普通会员功能',
      '无限视频观看',
      '无限视频下载',
      '1080P高清画质',
      '去广告体验',
      '优先客服支持',
      '专属会员标识',
      '会员专属内容'
    ],
    highlight: true
  },
  {
    id: 'vip',
    name: 'VIP会员',
    price: 168,
    period: '年',
    features: [
      '所有高级会员功能',
      '4K超高清画质',
      '专属VIP客服',
      '专属活动邀请',
      '生日特权礼包',
      '视频上传特权',
      '年度VIP专属礼物'
    ],
    highlight: false
  }
]

// 获取用户数据
const loadUserData = async () => {
  try {
    const currentUser = getCurrentUser()
    if (!currentUser) {
      router.push('/login')
      return
    }
    
    // 获取完整的用户信息
    const fullUser = getUserProfile(currentUser.id)
    if (fullUser) {
      userData.value = {
        ...fullUser,
        membership: fullUser.membership || {
          level: 'basic',
          expireDate: null,
          activatedDate: fullUser.createdAt
        }
      }
    } else {
      error.value = '获取用户信息失败'
    }
  } catch (err) {
    error.value = '加载会员信息失败'
    console.error('Failed to load membership data:', err)
  } finally {
    isLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '永久有效'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 计算会员有效期天数
const getDaysRemaining = () => {
  if (!userData.value?.membership?.expireDate) return null
  const today = new Date()
  const expireDate = new Date(userData.value.membership.expireDate)
  const diffTime = Math.abs(expireDate - today)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 选择会员套餐
const selectMembership = (level) => {
  if (!userData.value) return
  
  // 在实际项目中，这里应该调用支付API
  // 这里只是模拟支付成功后的操作
  
  const selectedLevel = membershipLevels.find(l => l.id === level)
  let expireDate = null
  
  if (level !== 'basic') {
    const now = new Date()
    if (level === 'premium') {
      now.setMonth(now.getMonth() + 1)
    } else if (level === 'vip') {
      now.setFullYear(now.getFullYear() + 1)
    }
    expireDate = now.toISOString()
  }
  
  const updatedUserData = {
    ...userData.value,
    membership: {
      level: level,
      activatedDate: new Date().toISOString(),
      expireDate: expireDate
    }
  }
  
  // 更新用户数据
  updateUserProfile(userData.value.id, updatedUserData)
  
  // 更新本地数据
  userData.value = updatedUserData
  
  alert(`会员升级成功！您现在是${selectedLevel.name}了。`)
}

// 导航到个人中心
const goToProfile = () => {
  router.push('/user/profile')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件挂载时加载用户数据
onMounted(() => {
  loadUserData()
})
</script>

<template>
  <div class="membership-container">
    <!-- 返回按钮 -->
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">会员中心</h1>
      <p class="page-subtitle">解锁更多高级功能，享受优质视频体验</p>
    </div>

    <!-- 用户当前会员状态 -->
    <div v-if="!isLoading && userData" class="current-membership">
      <div class="membership-card">
        <div class="membership-status">
          <div class="status-badge" :class="`status-${userData.membership.level}`">
            {{ membershipLevels.find(l => l.id === userData.membership.level)?.name || '普通用户' }}
          </div>
          <div class="status-info">
            <div class="expire-date">有效期至：{{ formatDate(userData.membership.expireDate) }}</div>
            <div v-if="getDaysRemaining()" class="days-remaining">
              {{ getDaysRemaining() }}天后到期
            </div>
          </div>
        </div>
        <button class="profile-btn" @click="goToProfile">
          查看个人中心
        </button>
      </div>
    </div>

    <!-- 会员套餐选择 -->
    <div class="membership-plans">
      <h2 class="section-title">选择会员套餐</h2>
      <div class="plans-grid">
        <div 
          v-for="plan in membershipLevels" 
          :key="plan.id"
          class="plan-card" 
          :class="{ 'plan-highlight': plan.highlight, 'plan-current': userData?.membership?.level === plan.id }"
        >
          <div class="plan-header">
            <h3 class="plan-name">{{ plan.name }}</h3>
            <div class="plan-price">
              <span class="price-number">{{ plan.price > 0 ? '¥' + plan.price : '免费' }}</span>
              <span v-if="plan.price > 0" class="price-period">/{{ plan.period }}</span>
            </div>
          </div>
          <div class="plan-features">
            <ul>
              <li v-for="(feature, index) in plan.features" :key="index">
                <svg class="feature-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <polyline points="20 6 9 17 4 12"></polyline>
                </svg>
                {{ feature }}
              </li>
            </ul>
          </div>
          <div class="plan-action">
            <button 
              class="select-btn"
              :class="{ 'btn-current': userData?.membership?.level === plan.id }"
              @click="selectMembership(plan.id)"
              :disabled="userData?.membership?.level === plan.id && plan.id !== 'basic'"
            >
              {{ userData?.membership?.level === plan.id ? '当前套餐' : '立即开通' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 会员特权说明 -->
    <div class="membership-benefits">
      <h2 class="section-title">会员特权</h2>
      <div class="benefits-grid">
        <div class="benefit-item">
          <div class="benefit-icon">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <polygon points="23 7 16 12 23 17 23 7"></polygon>
              <rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect>
            </svg>
          </div>
          <div class="benefit-content">
            <h3 class="benefit-title">高清画质</h3>
            <p class="benefit-description">享受1080P甚至4K超高清视频观看体验</p>
          </div>
        </div>
        <div class="benefit-item">
          <div class="benefit-icon">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>
              <polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline>
              <line x1="12" y1="22.08" x2="12" y2="12"></line>
            </svg>
          </div>
          <div class="benefit-content">
            <h3 class="benefit-title">去广告体验</h3>
            <p class="benefit-description">观看视频时不再受到广告打扰</p>
          </div>
        </div>
        <div class="benefit-item">
          <div class="benefit-icon">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
              <polyline points="7 10 12 15 17 10"></polyline>
              <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
          </div>
          <div class="benefit-content">
            <h3 class="benefit-title">视频下载</h3>
            <p class="benefit-description">下载视频随时随地离线观看</p>
          </div>
        </div>
        <div class="benefit-item">
          <div class="benefit-icon">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
              <circle cx="12" cy="7" r="4"></circle>
            </svg>
          </div>
          <div class="benefit-content">
            <h3 class="benefit-title">专属标识</h3>
            <p class="benefit-description">在评论区和个人主页展示尊贵会员标识</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 常见问题 -->
    <div class="faq-section">
      <h2 class="section-title">常见问题</h2>
      <div class="faq-list">
        <div class="faq-item">
          <div class="faq-question">如何开通会员？</div>
          <div class="faq-answer">
            在会员中心选择您喜欢的会员套餐，点击"立即开通"按钮，按照提示完成支付即可开通会员服务。
          </div>
        </div>
        <div class="faq-item">
          <div class="faq-question">会员可以退款吗？</div>
          <div class="faq-answer">
            根据平台规则，会员服务一旦开通，不支持退款。请谨慎选择会员套餐。
          </div>
        </div>
        <div class="faq-item">
          <div class="faq-question">会员到期后会自动续费吗？</div>
          <div class="faq-answer">
            目前平台不会自动续费，会员到期前我们会提醒您手动续费。
          </div>
        </div>
        <div class="faq-item">
          <div class="faq-question">会员特权可以在多个设备上使用吗？</div>
          <div class="faq-answer">
            是的，您可以在多个设备上登录同一账号，享受会员特权。
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.membership-container {
  min-height: calc(100vh - 60px);
  background-color: var(--background-color);
  padding-top: 20px;
}

/* 返回按钮 */
.back-button {
  position: fixed;
  top: 70px;
  left: 20px;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background-color: var(--white);
  border: 1px solid var(--border-color);
  border-radius: 20px;
  font-size: 14px;
  color: var(--text-primary);
  cursor: pointer;
  z-index: 100;
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: var(--hover-background);
  border-color: var(--primary-color);
  color: var(--primary-color);
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 0 20px;
}

.page-title {
  font-size: 36px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 12px;
}

.page-subtitle {
  font-size: 18px;
  color: var(--text-secondary);
  max-width: 600px;
  margin: 0 auto;
}

/* 当前会员状态 */
.current-membership {
  max-width: 1200px;
  margin: 0 auto 60px;
  padding: 0 20px;
}

.membership-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 32px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: var(--shadow-md);
}

.membership-status {
  flex: 1;
}

.status-badge {
  display: inline-block;
  padding: 6px 20px;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  background-color: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.status-basic {
  background-color: rgba(255, 255, 255, 0.2);
}

.status-premium {
  background-color: rgba(255, 215, 0, 0.3);
  color: #fff;
}

.status-vip {
  background-color: rgba(255, 140, 0, 0.3);
  color: #fff;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.expire-date {
  font-size: 18px;
  font-weight: 500;
}

.days-remaining {
  font-size: 14px;
  opacity: 0.9;
}

.profile-btn {
  background-color: white;
  color: #667eea;
  padding: 12px 32px;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
}

.profile-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.3);
}

/* 会员套餐选择 */
.membership-plans {
  max-width: 1200px;
  margin: 0 auto 80px;
  padding: 0 20px;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 32px;
  text-align: center;
}

.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.plan-card {
  background-color: var(--white);
  border-radius: 16px;
  padding: 32px;
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.plan-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-md);
}

.plan-highlight {
  border-color: #667eea;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
}

.plan-current {
  border-color: var(--success-color);
  position: relative;
}

.plan-current::before {
  content: '当前套餐';
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: var(--success-color);
  color: white;
  padding: 2px 16px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.plan-header {
  margin-bottom: 24px;
}

.plan-name {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 12px;
}

.plan-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.price-number {
  font-size: 32px;
  font-weight: 700;
  color: var(--primary-color);
}

.price-period {
  font-size: 16px;
  color: var(--text-secondary);
}

.plan-features {
  margin-bottom: 32px;
}

.plan-features ul {
  list-style: none;
}

.plan-features li {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
  color: var(--text-primary);
  line-height: 1.5;
}

.feature-icon {
  margin-top: 2px;
  flex-shrink: 0;
  color: var(--success-color);
}

.plan-action {
  text-align: center;
}

.select-btn {
  width: 100%;
  padding: 12px 24px;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 600;
  background-color: var(--primary-color);
  color: white;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.select-btn:hover {
  background-color: var(--primary-color-hover);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(251, 114, 153, 0.3);
}

.btn-current {
  background-color: var(--success-color);
  cursor: not-allowed;
}

.btn-current:hover {
  background-color: var(--success-color);
  transform: none;
  box-shadow: none;
}

/* 会员特权 */
.membership-benefits {
  max-width: 1200px;
  margin: 0 auto 80px;
  padding: 0 20px;
}

.benefits-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 32px;
}

.benefit-item {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.benefit-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #f0f4ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #667eea;
  flex-shrink: 0;
}

.benefit-content {
  flex: 1;
}

.benefit-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.benefit-description {
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.6;
}

/* 常见问题 */
.faq-section {
  max-width: 1200px;
  margin: 0 auto 80px;
  padding: 0 20px;
}

.faq-list {
  max-width: 800px;
  margin: 0 auto;
}

.faq-item {
  margin-bottom: 24px;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 24px;
}

.faq-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.faq-question {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 12px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.faq-question:hover {
  color: var(--primary-color);
}

.faq-answer {
  font-size: 16px;
  color: var(--text-secondary);
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .back-button {
    top: 10px;
    left: 10px;
    background-color: rgba(255, 255, 255, 0.9);
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .page-subtitle {
    font-size: 16px;
  }
  
  .membership-card {
    flex-direction: column;
    gap: 24px;
    text-align: center;
  }
  
  .plans-grid {
    grid-template-columns: 1fr;
  }
  
  .benefits-grid {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .benefit-item {
    flex-direction: column;
    text-align: center;
    align-items: center;
  }
  
  .faq-question {
    font-size: 16px;
  }
  
  .faq-answer {
    font-size: 14px;
  }
}
</style>